package org.btik.light.mobile.ui.serial.controller;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import org.btik.context.SimpleContext;

import static org.btik.light.mobile.platform.conf.ContextGlobalNames.USB_PERMISSION_CALLBACK;
import static org.btik.light.mobile.ui.serial.controller.SerialControllerMainFragment.ACTION_USB_PERMISSION;

/**
 * @author lustre
 * @since 2023/4/30 10:45
 */
public class UsbPermissionReceiver extends BroadcastReceiver {


    private static boolean regDone = false;

    @Override
    public void onReceive(Context context, Intent intent) {
        // 目前intent 未携带是否授权成功，callback中自行判断，故一定执行callback
        Runnable callback = SimpleContext.remove(USB_PERMISSION_CALLBACK);
        if (callback == null) {
            return;
        }
        try {
            callback.run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void reg(Activity activity) {
        if (regDone) {
            return;
        }
        UsbPermissionReceiver usbPermissionReceiver = new UsbPermissionReceiver();
        IntentFilter intentFilter = new IntentFilter(ACTION_USB_PERMISSION);
        activity.registerReceiver(usbPermissionReceiver, intentFilter);
        regDone = true;
    }


}
